package com.example.gcmtest1.youtube;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.util.RandomAccess;

public class MyRandomWriter {

	private String fileName;
	private RandomAccessFile fs;
	
	public MyRandomWriter(String fileName) throws FileNotFoundException {
		this.fileName = fileName;
		this.fs = new RandomAccessFile(fileName, "rw");
		
	}
	
	public void testWrite() throws IOException {
		this.fs.write(1);
		
	}
	
	public void write(byte[] b, int start, int len) throws IOException {
		this.fs.write(b, start, len);
	}
	
	public void setFileSize(long fileSize) throws IOException {
		if (this.fs != null) {
			this.fs.setLength(fileSize);
		}
	}
	
	public void done() throws IOException {
		if (this.fs != null) {
			this.fs.close();
		}
	}

	public static void copyFile(InputStream is, String dest) throws IOException {
		OutputStream out = new FileOutputStream(dest);
		
		byte[] buffer = new byte[1024];
		int length;
		while ((length = is.read(buffer)) > 0) {
			out.write(buffer, 0, length);
		}
		
		out.flush();
		out.close();
		is.close();
	}
	
	public static void copyFile(String src, String dest) throws IOException {
		InputStream is = new FileInputStream(src);
		OutputStream out = new FileOutputStream(dest);
		
		byte[] buffer = new byte[1024];
		int length;
		while ((length = is.read(buffer)) > 0) {
			out.write(buffer, 0, length);
		}
		
		out.flush();
		out.close();
		is.close();
	}
	
	
}
